﻿using BLL;
using DAL;
using DAL.Dao;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using DataProj.Areas.BackSys.ServiceTools;
using MQTools;
using System.Text.Json.Serialization;
using Newtonsoft.Json;

namespace DataProj.Areas.BackSys.Controllers
{
    public class BagController : BaseController
    {

        private static BagInfoImpl _impl;
        // GET: Bag

        public BagController()
        {
            if (_impl == null) _impl = new BagInfoImpl();
            if (string.IsNullOrEmpty(MySession.GetSession("senderRows")))
            {
                MySession.WriteSession("senderRows", 10);
            }

            if (string.IsNullOrEmpty(MySession.GetSession("senderPage")))
            {
                MySession.WriteSession("senderPage", 1);
            }
            if (string.IsNullOrEmpty(MySession.GetSession("getterRows")))
            {
                MySession.WriteSession("getterRows", 10);
            }
            if (string.IsNullOrEmpty(MySession.GetSession("getterPage")))
            {
                MySession.WriteSession("getterPage", 1);
            }
            if (string.IsNullOrEmpty(MySession.GetSession("bagRows")))
            {
                MySession.WriteSession("bagRows", 10);
            }
            if (string.IsNullOrEmpty(MySession.GetSession("bagPage")))
            {
                MySession.WriteSession("bagPage", 1);
            }

        }
        //public new ActionResult Index()
        //{
            
        //    return PartialView(_impl.GetList());
        //}


        public ActionResult BagSend()
        {
            

                switch (LoginType)
                {
                    case "用户":
                        
                        return RedirectToAction("Index","Home");
                    case "管理员":
                    case "快递员":
                        int rows = Convert.ToInt16(MySession.GetSession("bagRows"));
                        int page = Convert.ToInt16(MySession.GetSession("bagPage"));
                        (var totalPages, var data) = _impl.GetList(rows, page);
                        MySession.WriteSession("bagTotalPages", totalPages);
                        ViewBag.BagList = data;
                    return PartialView();
                default:
                        break;
                }
            
            return PartialView();
        }


        [HttpPost]
        public ActionResult ChangePage()
        {
            IDictionary<string, string> set = new Dictionary<string, string>();
            switch (Request["action"])
            {
                case "sender":
                    int senderPage = Convert.ToInt16(Request["senderPage"].Trim());
                    //MySession.WriteSession("senderPage", senderPage);
                    int senderRows = Convert.ToInt16(MySession.GetSession("senderRows"));
                    UserInfo d1 = MySession.GetSession_UserInfo("detail");
                    (var senderTotalPages , var senderBagList ) = _impl.GetSenderList(d1.UserName, d1.Phone, senderRows, senderPage );
                    //MySession.WriteSession("senderTotalPages", senderTotalPages);
                    set.Add("totalPages", senderTotalPages.ToString());
                    set.Add("data", JsonConvert.SerializeObject(senderBagList));
                    return Json(JsonConvert.SerializeObject(set));
                    //return Json(JsonConvert.SerializeObject(senderBagList));
                case "getter":
                    int getterPage = Convert.ToInt16(Request["getterPage"].Trim());
                    //MySession.WriteSession("getterPage", getterPage);
                    int getterRows = Convert.ToInt16(MySession.GetSession("getterRows"));
                    UserInfo d2 = MySession.GetSession_UserInfo("detail");
                    (var getterTotalPages , var getterBagList) = _impl.GetGetterList(d2.UserName, d2.Phone, getterRows, getterPage);
                    //MySession.WriteSession("getterTotalPages", getterTotalPages);
                    //return Json(JsonConvert.SerializeObject(getterBagList));
                    set.Add("totalPages", getterTotalPages.ToString());
                    set.Add("data", JsonConvert.SerializeObject(getterBagList));
                    return Json(JsonConvert.SerializeObject(set));
                case "total":
                    int page = Convert.ToInt16(Request["pageNum"].Trim());
                    //MySession.WriteSession("bagPage", page);
                    int rows = Convert.ToInt16(MySession.GetSession("bagRows"));
                    (var bagTotalPages, var bagList) = _impl.GetList(rows, page);
                    MySession.WriteSession("bagTotalPages", bagTotalPages);
                    //return Json(JsonConvert.SerializeObject(bagList));
                    set.Add("totalPages", bagTotalPages.ToString());
                    set.Add("data", JsonConvert.SerializeObject(bagList));
                    return Json(JsonConvert.SerializeObject(set));
                default:
                    break;
            }
            return Json(0);
        }


        public ActionResult BagManage()
        {


            //switch (LoginType)
            //{
            //    case "用户":

            //            UserInfo detail = MySession.GetSession_UserInfo("detail");
            //            int senderRows = Convert.ToInt16(MySession.GetSession("senderRows"));
            //            int senderPage = Convert.ToInt16(MySession.GetSession("senderPage"));
            //            int getterRows = Convert.ToInt16(MySession.GetSession("getterRows"));
            //            int getterPage = Convert.ToInt16(MySession.GetSession("getterPage"));
            //        (var total_nums, var ans) = _impl.GetList(detail.UserName, detail.Phone, senderRows, senderPage, getterRows, getterPage);
            //            //ViewBag.SenderBagList = ans[0];
            //        //MySession.WriteSession("senderTotalPages", total_nums[0]);
            //            //ViewBag.GetterBagList = ans[1];
            //        //MySession.WriteSession("getterTotalPages", total_nums[1]);
            //        return PartialView();
            //    case "管理员":
            //    case "快递员":
            //        int rows = Convert.ToInt16(MySession.GetSession("bagRows"));
            //        int page = Convert.ToInt16(MySession.GetSession("bagPage"));
            //        (var totalPages,var data) = _impl.GetList(rows, page);
            //        MySession.WriteSession("bagTotalPages", totalPages);
            //        ViewBag.BagList = data;
            //        return PartialView();
            //    default:
            //        break;
            //}
            //return PartialView(_impl.GetList());
            return PartialView();
        }
        public ActionResult BagRegister()
        {

                switch (LoginType)
                {
                    case "用户":
                        UserInfo detail =  MySession.GetSession_UserInfo("detail");
                        return PartialView(detail);
                    case "管理员":
                    case "快递员":
                        return RedirectToAction("Index","Home");
                    default:
                        break;
                }
         
            return PartialView();
        }




        [HttpPost]
        public ActionResult GetItemByID(string id,string action)
        {
            var tool = new JavaScriptSerializer();
            //string get = MyRequest.GetQueryString();
            //Task obj = tool.DeserializeObject(get) as Task;
            var result = _impl.GetItemByID(id);
            string seri = tool.Serialize(result);
            return Json(seri);
        }
        [HttpPost]
        public ActionResult Delete()
        {
            
            var tool = new JavaScriptSerializer();
            string bagID = Convert.ToString(Request["ID"]).Trim();
            if (_impl.DeleteBagInfo(bagID) == true)
            {
                if (LoginType.Equals("用户"))
                {
                    MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.BAG_DELETE,
                        Bag = new Bag() { BagID = bagID },
                        User = new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID")) }
                    }, Resources.CompanyBagRoute);
                }
                else
                {
                    MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.BAG_DELETE,
                        Bag = new Bag() { BagID = bagID },
                        User = new UserInfo() { ID = _impl.GetSenderUserIDByBagID(bagID) }
                    }, Resources.CustomerBagRoute);
                }
                //删除成功
                return Json(1);
            }
            //删除失败
            return Json(0);
        }

        [HttpPost]
        public ActionResult Update()
        {
            //var tool = new JavaScriptSerializer();
            //string get = MyRequest.GetQueryString();
            //Task_Update obj = tool.DeserializeObject(get) as Task_Update;
            Bag update_item = new Bag();
            switch (Request["Action"].Trim())
            {
                case "delivery_begin":
                    update_item.BagID = Convert.ToString(Request["ID"]).Trim();
                    update_item.UpdateTime = DateTime.Now;
                    if (_impl.DeliveryBag(update_item.BagID, update_item))
                    {
                        if (LoginType.Equals("用户"))
                        {
                            MqSender.SendMessage(new QueueMessage()
                            {
                                Action = QueueMessage.ActionType.BAG_UPDATE,
                                Bag = update_item,
                                User = new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID")) }
                            }, Resources.CompanyBagRoute);
                        }
                        else
                        {
                            int id = _impl.GetSenderUserIDByBagID(update_item.BagID);
                            if (id != -1)
                            {
                                MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { ID = id }
                                }, Resources.CustomerBagRoute);
                            }
                          
                        }

                        return Json(1);
                    }
                    break;
                case "delivery_finish":
                    update_item.BagID = Convert.ToString(Request["ID"]).Trim();
                    update_item.ArriveDate = update_item.UpdateTime = DateTime.Now;
                    if (_impl.FinishDeliveryingBag(update_item.BagID, update_item))
                    {
                        if (LoginType.Equals("用户"))
                        {
                            MqSender.SendMessage(new QueueMessage()
                            {
                                Action = QueueMessage.ActionType.BAG_UPDATE,
                                Bag = update_item,
                                User = new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID")) }
                            }, Resources.CompanyBagRoute);
                        }
                        else
                        {

                            int id = _impl.GetSenderUserIDByBagID(update_item.BagID);
                            if (id != -1)
                            {
                                MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { ID = id }
                                }, Resources.CustomerBagRoute);
                            }
                        }

                        return Json(1);
                    }
                    
                    break;
                case "update":
                    update_item.BagID = Convert.ToString(Request["ID"]).Trim();
                    //update_item.SendDate = Convert.ToDateTime(Request["SendDate"]);
                    update_item.GetterName = Convert.ToString(Request["GetterName"]).Trim();
                    update_item.GetterPhone = Convert.ToString(Request["GetterPhone"]).Trim();
                    update_item.GetterAddress = Convert.ToString(Request["GetterAddress"]).Trim();
                    update_item.SenderName = Convert.ToString(Request["SenderName"]).Trim();
                    update_item.SenderPhone = Convert.ToString(Request["SenderPhone"]).Trim();
                    update_item.SenderAddress = Convert.ToString(Request["SenderAddress"]).Trim();
                    update_item.SendInfo = Convert.ToString(Request["SendInfo"]).Trim();
                    update_item.UpdateTime = DateTime.Now;
                    if (_impl.UpdateBag(update_item.BagID, update_item))
                    {
                        if (LoginType.Equals("用户"))
                        {
                            MqSender.SendMessage(new QueueMessage()
                            {
                                Action = QueueMessage.ActionType.BAG_UPDATE,
                                Bag = update_item,
                                User = new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID")) }
                            }, Resources.CompanyBagRoute);
                        }
                        else
                        {
                            int id = _impl.GetSenderUserIDByBagID(update_item.BagID);
                            if (id != -1)
                            {
                                MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { ID = id }
                                }, Resources.CustomerBagRoute);
                            }
                        }

                        return Json(1);
                    }
                    break;
                default:
                    break;
            }
          

            //string get = MyRequest.GetQueryString();
            //Task obj = tool.DeserializeObject(get) as Task;

            return Json(0);
        }


        [HttpPost]
        public ActionResult Add()
        {
            
            Bag bag = new Bag();
            bag.SendDate = DateTime.Now;
            bag.BagID = "8888" + DateTime.Now.ToString("yyyyMMddhhmmss");
            bag.GetterName = Request["GetterName"];
            bag.GetterPhone = Request["GetterPhone"];
            bag.GetterAddress = Request["GetterAddress"];
            bag.SenderName = Request["SenderName"];
            bag.SenderPhone = Request["SenderPhone"];
            bag.SenderAddress = Request["SenderAddress"];
            bag.SendInfo = Request["SendInfo"];
            bag.ArriveInfo= "运输中";
            bag.AddTime = DateTime.Now;
            //bag.ArriveInfo =Request["ArriveInfo"];
            if(!_impl.Add(bag))return Json(0) ;

            
            QueueMessage queueMessage = new QueueMessage() { Action=QueueMessage.ActionType.BAG_REGISTRER, Bag=bag,User=new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID")) }  };
            MqSender.SendMessage(queueMessage,Resources.CompanyBagRoute);
            return Json(1);   
        }

        //
        // GET: /BackSys/Bag/Edit/5

        public ActionResult Find(int id = 0)
        {
            //if (Session[Common.UserLoginSessionKey] != null)
            //{

            //}
            Bag bag = _impl.Find(id);
            if (bag == null)
            {
                return HttpNotFound();
            }
            return PartialView(bag);
        }
        //
        // POST: /BackSys/Bag/Edit/5

        [HttpPost]
        public ActionResult Edit(Bag bag)
        {
            if (ModelState.IsValid)
            {
                bag.UpdateTime = DateTime.Now;
                _impl.Edit(bag);
                return RedirectToAction("Index");
            }
            return PartialView(bag);
        }



        protected override void Dispose(bool disposing)
        {
            _impl.Dispose();
            base.Dispose(disposing);
        }

    }
}